package com.durian.base.net;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 说明：HttpTaskManager
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019/1/30 15:58
 * <p/>
 * 版本：version 1.0
 */
public class DownloadTaskManager {

    private static Handler             sHandler;
    private static DownloadTaskManager mHandler;
    private        ExecutorService     mExecutorService;
    private        ConcurrentHashMap<String, Future> mFutureMap;

    private DownloadTaskManager() {
        sHandler = new Handler(Looper.getMainLooper());
        mExecutorService = Executors.newFixedThreadPool(3);
        mFutureMap = new ConcurrentHashMap<>();
    }

    public static DownloadTaskManager get() {
        synchronized (DownloadTaskManager.class) {
            if (mHandler == null) {
                mHandler = new DownloadTaskManager();
            }
        }
        return mHandler;
    }

    public Handler getHandler() {
        return sHandler;
    }

    public void addTask(IHttpTask task) {
        if (task != null && mExecutorService != null) {
            Future future = mExecutorService.submit(task);
            if (mFutureMap != null && future != null && !TextUtils.isEmpty(task.getTaskId())) {
                mFutureMap.put(task.getTaskId(), future);
            }
        }
    }

    public void removeTaskId(String taskId){
        if (!TextUtils.isEmpty(taskId) && mFutureMap != null && mFutureMap.containsKey(taskId)) {
            Future future;
            try {
                future = mFutureMap.remove(taskId);
                if (future != null) {
                    future.cancel(true);
                }
                Utils.vLog("当前请求Map中数量" + mFutureMap.size());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void removeTask(IHttpTask task) {
        if (task != null){
            removeTaskId(task.getTaskId());
        }
    }

}
